<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <div class="header" style="display: flex; align-items: center; margin-bottom: 20px;">
        <h2 style="margin-right: auto;">入住合同管理</h2>
      </div>

      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="12">
          <el-card shadow="hover" class="statistics-card">
            <div slot="header" class="clearfix">
              <span>合同统计信息</span>
            </div>
            <div class="statistics">
              <div class="stat-item">
                <i class="el-icon-document stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">总合同数</p>
                  <p class="stat-value">{{ contractList.length }}</p>
                </div>
              </div>
              <div class="stat-item">
                <i class="el-icon-circle-check stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">有效合同</p>
                  <p class="stat-value">{{ validContracts }}</p>
                </div>
              </div>
              <div class="stat-item">
                <i class="el-icon-circle-close stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">已过期合同</p>
                  <p class="stat-value">{{ expiredContracts }}</p>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>合同提醒</span>
              <el-button type="primary" icon="el-icon-plus" @click="addReminder" style="float: right;">新增提醒</el-button>
            </div>
            <ul class="reminder-list">
              <li v-for="(reminder, index) in contractReminders" :key="index">
                <i class="el-icon-warning-outline reminder-icon"></i>
                {{ reminder.reminder }}
                <el-button type="text" @click="editReminder(reminder)">编辑</el-button>
                <el-button type="text" @click="deleteReminder(reminder)" class="delete-btn">删除</el-button>
              </li>
            </ul>
          </el-card>
        </el-col>
      </el-row>

      <el-input
          v-model="searchKeyword"
          placeholder="搜索合同编号或老人姓名"
          prefix-icon="el-icon-search"
          style="width: 300px; margin-right: 20px;"
          @keyup.enter.native="searchContracts"
        ></el-input>
        <el-button type="primary" icon="el-icon-plus" @click="addContract">新增合同</el-button>
      <el-table :data="filteredContracts" style="width: 100%" border stripe>
        <el-table-column prop="contractNumber" label="合同编号" width="150"></el-table-column>
        <el-table-column prop="elderlyName" label="老人姓名" width="150"></el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="150"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '有效' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="editContract(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteContract(scope.row)" class="delete-btn">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增/编辑合同对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="合同编号">
            <el-input v-model="form.contractNumber"></el-input>
          </el-form-item>
          <el-form-item label="老人姓名">
            <el-input v-model="form.elderlyName"></el-input>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="form.startDate" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker v-model="form.endDate" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="选择状态">
              <el-option label="有效" value="有效"></el-option>
              <el-option label="已过期" value="已过期"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑提醒对话框 -->
      <el-dialog :title="reminderDialogTitle" :visible.sync="reminderDialogVisible" width="50%">
        <el-form :model="reminderForm" label-width="120px">
          <el-form-item label="提醒内容">
            <el-input v-model="reminderForm.reminder"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="reminderDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleReminderSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue'
import axios from 'axios'

export default {
  name: 'AdmissionContract',
  components: {
    AsideLayout
  },
  data() {
    return {
      searchKeyword: '',
      contractList: [],
      filteredContracts: [],
      contractReminders: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        contractNumber: '',
        elderlyName: '',
        startDate: '',
        endDate: '',
        status: ''
      },
      reminderDialogVisible: false,
      reminderDialogTitle: '',
      reminderForm: {
        id: null,
        reminder: ''
      }
    }
  },
  computed: {
    validContracts() {
      return this.contractList.filter(contract => contract.status === '有效').length
    },
    expiredContracts() {
      return this.contractList.filter(contract => contract.status === '已过期').length
    }
  },
  mounted() {
    this.fetchContracts()
    this.fetchReminders()
    this.filteredContracts = this.contractList;
  },
  methods: {
    fetchContracts() {
      axios.get('http://localhost:3000/api/contracts')
        .then(response => {
          this.contractList = response.data
          this.filteredContracts = response.data;
        })
        .catch(error => {
          console.error('Error fetching contracts:', error)
        })
    },
    fetchReminders() {
      axios.get('http://localhost:3000/api/contract-reminders')
        .then(response => {
          this.contractReminders = response.data
        })
        .catch(error => {
          console.error('Error fetching reminders:', error)
        })
    },
    addContract() {
      this.dialogTitle = '新增合同'
      this.form = {
        id: null,
        contractNumber: '',
        elderlyName: '',
        startDate: '',
        endDate: '',
        status: ''
      }
      this.dialogVisible = true
    },
    searchContracts() {
      console.log('搜索关键词:', this.searchKeyword);
      this.filteredContracts = this.contractList.filter(contract =>
        contract.contractNumber === this.searchKeyword || contract.elderlyName === this.searchKeyword
      );
      console.log('过滤后的合同:', this.filteredContracts);
      this.$message.success(`搜索功能已实现，关键词：${this.searchKeyword}`);
    },
    exportContracts() {
      this.$message.success('导出合同功能待实现')
    },
    viewDetails(row) {
      this.$message.success(`查看详情功能待实现，合同编号：${row.contractNumber}`)
    },
    editContract(row) {
      this.dialogTitle = '编辑合同'
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleSubmit() {
      if (this.form.id) {
        axios.put(`http://localhost:3000/api/contracts/${this.form.id}`, this.form)
          .then(() => {
            this.fetchContracts()
            this.dialogVisible = false
            this.$message.success('更新合同成功')
          })
          .catch(error => {
            console.error('Error updating contract:', error)
            this.$message.error('更新合同失败')
          })
      } else {
        axios.post('http://localhost:3000/api/contracts', this.form)
          .then(() => {
            this.fetchContracts()
            this.dialogVisible = false
            this.$message.success('新增合同成功')
          })
          .catch(error => {
            console.error('Error adding contract:', error)
            this.$message.error('新增合同失败')
          })
      }
    },
    deleteContract(row) {
      this.$confirm(`确认删除合同 ${row.contractNumber} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/contracts/${row.id}`)
          .then(() => {
            this.fetchContracts()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting contract:', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    addReminder() {
      this.reminderDialogTitle = '新增提醒'
      this.reminderForm = {
        id: null,
        reminder: ''
      }
      this.reminderDialogVisible = true
    },
    editReminder(reminder) {
      this.reminderDialogTitle = '编辑提醒'
      this.reminderForm = { ...reminder }
      this.reminderDialogVisible = true
    },
    handleReminderSubmit() {
      if (this.reminderForm.id) {
        axios.put(`http://localhost:3000/api/contract-reminders/${this.reminderForm.id}`, this.reminderForm)
          .then(() => {
            this.fetchReminders()
            this.reminderDialogVisible = false
            this.$message.success('更新提醒成功')
          })
          .catch(error => {
            console.error('Error updating reminder:', error)
            this.$message.error('更新提醒失败')
          })
      } else {
        axios.post('http://localhost:3000/api/contract-reminders', this.reminderForm)
          .then(() => {
            this.fetchReminders()
            this.reminderDialogVisible = false
            this.$message.success('新增提醒成功')
          })
          .catch(error => {
            console.error('Error adding reminder:', error)
            this.$message.error('新增提醒失败')
          })
      }
    },
    deleteReminder(reminder) {
      this.$confirm(`确认删除提醒 ${reminder.reminder} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/contract-reminders/${reminder.id}`)
          .then(() => {
            this.fetchReminders()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting reminder:', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.el-container {
  height: 100vh;
}

.el-main {
  padding: 20px;
  overflow-y: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
}

.el-table {
  border-radius: 5px;
  overflow: hidden;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.statistics {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 5px;
}

.stat-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 10px;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.reminder-list {
  list-style: none;
  padding: 0;
}

.reminder-list li {
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}

.reminder-icon {
  font-size: 18px;
  color: #E6A23C;
  margin-right: 10px;
}
</style>